package com.thyrsus.project.helper;

import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.propertyeditors.LocaleEditor;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.support.RequestContextUtils;

public class LocaleHelper {
	
	static Logger LOGGER = Logger.getLogger(LocaleHelper.class);

	public static void setLocale(String lang,HttpServletRequest request,HttpServletResponse response) {
		LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);                

        if (localeResolver != null) {
            if (lang != null) {
            	
            	LOGGER.debug("The new locale is : "+lang);
            	
                LocaleEditor localeEditor = new LocaleEditor();
                localeEditor.setAsText(lang);
                localeResolver.setLocale(request, response,
                    (Locale) localeEditor.getValue());
            }
        }
	}
	public static void setLocale(Locale lang,HttpServletRequest request,HttpServletResponse response) {
		LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);                

        if (localeResolver != null) {
            if (lang != null) {
                localeResolver.setLocale(request, response,lang);
            }
        }
	}
	public static String getLocale(HttpServletRequest request) {
		LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);
		Locale locale = localeResolver.resolveLocale(request);
		LOGGER.debug("The resolved locale is : "+locale.getLanguage());
		
		return locale.getLanguage();
	}
	
	public static void manageLocale(HttpServletRequest request,HttpServletResponse response) {
		setLocale(getLocale(request),request,response);
	}
}
